<?php
/**
 *
 * Author:苏光盼
 * web:https://api.jifen.suanzisu.com
 * date:2019/12/28 下午4:07
 * class:Privileges.php
 * Project:通用APP后台管理系统
 *
 */

namespace App\Model;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\Http\Message\Status;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\Exception\Exception;
class Privileges extends AbstractModel
{
    protected $tableName = 'privileges';
    protected $autoTimeStamp = false;
    protected $updateTime = false;


    protected static function onBeforeInsert(self $model )
    {
        $is_has = $model->where('url',$model->url)->count();
         if( $is_has > 0 ) throw new Exception('有重复的URL',Status::CODE_NOT_ACCEPTABLE);

    }


    /**
     * @param Privileges $model
     * @param $BeforeUpdateData
     * 修改之前
     *
     * @return bool
     * @throws Exception
     * @throws \Throwable
     */
    protected static function onBeforeUpdate( self $model,$BeforeUpdateData )
    {
           if( isset( $BeforeUpdateData['url'])) {
               $model->where('id',$BeforeUpdateData['id'],'<>')->where('url',$BeforeUpdateData['url']);
               $is_has  = $model->count();
               if( $is_has > 0 )
                   throw new Exception('有重复URL，请修改！',Status::CODE_CONFLICT);
           }
           return true;

    }

    /**
     * @param Privileges $mode
     * @param $deleteId
     * 删除之前的事件 删除之前，要检查是否有表在使用该id
     *
     * @return bool
     * @throws Exception
     * @throws \Throwable
     */
    protected static function onBeforeDelete(self $mode)
    {
        TaskManager::getInstance()->async(function () use ($mode){
            GroupPriMap::create()->where('pri_id',$mode->id)->destroy();
        });
    }


}